package cn.scw.common.utils.http;

import cn.scw.common.constant.PrintConsts;
import cn.scw.common.exception.CustomException;
import cn.scw.project.facility.domain.FacPrintOrder;
import cn.scw.project.facility.domain.pojo.PrintSetting;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: lj
 * @create: 2020-06-20
 **/
public class HttpPrintUtils {

    public static boolean print(FacPrintOrder order) {
        boolean print = false;
        String content = order.getContent();
        System.out.println("打印内容：" + content);
        String token = login(order.getFacilityCode());
        if (content.startsWith("{") && content.endsWith("}")) {

        } else if (content.contains(",")) {
            String[] list = content.split(",");
            for (String s : list) {
                order.setContent(s);
                PrintSetting setting = new PrintSetting(order);
                JSONObject printJson = createInternetPrint(token, setting);
                if (printJson == null) throw new CustomException("打印机连接失败");
                postData(printJson.getString("UploadUri"), setting);
                print = print(token, printJson.getString("JobId"));
                if (print) System.out.println("打印成功");
                else System.out.println("打印失败");
            }
        } else {
            PrintSetting setting = new PrintSetting(order);
            JSONObject printJson = createInternetPrint(token, setting);
            if (printJson == null) throw new CustomException("打印机连接失败");
            postData(printJson.getString("UploadUri"), setting);
            print = print(token, printJson.getString("JobId"));
            if (print) System.out.println("打印成功");
            else System.out.println("打印失败");
        }
        return print;
    }


    /**
     * 登录
     *
     * @return token
     */
    private static String login(String code) {
        String url = "https://www.epsonconnect.com/remoteprint/v1/Login";

        JSONObject param = new JSONObject();
        param.put("AuthType", "PrinterMailAddress");    // 固定值
        param.put("DeviceId", code);  // 打印机的设备注册id
        param.put("AccessKey", ""); // 固定值
        param.put("ClientInfo", "iPrint/Android 5.1.1/zh"); // 固定值
        param.put("ClientId", "d1e3913a79d74781bbe303e900ae2a90");  // 未知，固定长度
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("Param", param);
        try {
            HttpClientResult result = HttpClientUtils.doPost(url, getHeader(), jsonParam);
            System.out.println(result.getCode() + "||" + result.getContent());
            JSONObject req = JSON.parseObject(result.getContent());
            if (req == null)
                throw new CustomException("打印机连接失败");
            return req.getString("Result");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建打印任务
     *
     * @param token token
     * @return
     */
    private static JSONObject createInternetPrint(String token, PrintSetting setting) {
        String url = "https://www.epsonconnect.com/remoteprint/v1/CreateInternetPrint?token=" + token;
        JSONObject printSettings = new JSONObject();
        printSettings.put("MediaSizeId", setting.getSize());    // 打印尺寸：0-A4，210*297毫米；4-A6，105*148毫米
        printSettings.put("MediaTypeId", setting.getType());
        printSettings.put("Borderless", false);
        printSettings.put("PrintQuality", setting.getQuality());    // 打印质量：High-高；Normal-标准
        printSettings.put("PaperSource", setting.getPaper()); // 进纸器：Rear-后进纸器；Front1-前进纸器
        printSettings.put("ColorMode", setting.getColor());    // 打印颜色：Color-彩色；Mono-黑白
        printSettings.put("TwoSidePrinting", "None");
        printSettings.put("Copies", setting.getCopies()); // 打印份数
        printSettings.put("Collate", setting.isCollate());    // 打印类型：false-照片；true-文档
        printSettings.put("Brightness", 0);
        printSettings.put("Contrast", 0);
        printSettings.put("Saturation", 0);

        JSONObject param = new JSONObject();
        param.put("PrintSettings", printSettings);  // 打印设置
        param.put("JobName", setting.getJobName());  // 文件名称
        param.put("PrintMode", setting.getMode());    // 打印类型：photo-照片；doc-文档

        JSONObject jsonParam = new JSONObject();
        jsonParam.put("Param", param);
        System.out.println(jsonParam.toJSONString());
        try {
            HttpClientResult result = HttpClientUtils.doPost(url, getHeader(), jsonParam);
            System.out.println(result.getCode() + "||" + result.getContent());
            JSONObject req = JSON.parseObject(result.getContent());
            if (req == null)
                throw new CustomException("打印机连接失败");
            return JSON.parseObject(req.getString("Result"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param url
     */
    private static void postData(String url, PrintSetting setting) {
        System.out.println("打印内容1：" + url);
        File file = new File(setting.getUrl());

        long imgByte = file.length();
        if (PrintConsts.PRINT_MODE_PHOTO.equals(setting.getMode()))
            url += "&File=1.jpg&start=0&end=" + imgByte + "&total=" + imgByte;
        else {
            String fileSuffix = setting.getJobName().substring(setting.getJobName().lastIndexOf(".")).toLowerCase();
            url += "&File=1" + fileSuffix + "&start=0&end=" + imgByte + "&total=" + imgByte;
        }
        try {
            HttpClientResult result = HttpClientUtils.doPost(url, getHeader(setting.getMode()), file);
            System.out.println(result.getCode() + "||" + result.getContent());
            System.out.println("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean print(String token, String JobId) {
        String url = "https://www.epsonconnect.com/remoteprint/v1/RequestPrinting?token=" + token + "&jobid=" + JobId;
        JSONObject param = new JSONObject();
        param.put("ServiceName", "iPrint");
        param.put("ClientId", "d1e3913a79d74781bbe303e900ae2a24");

        JSONObject jsonParam = new JSONObject();
        jsonParam.put("Param", param);
        try {
            HttpClientResult result = HttpClientUtils.doPost(url, getHeader(), jsonParam);
            System.out.println(result.getCode() + "||" + result.getContent());
            JSONObject req = JSON.parseObject(result.getContent());
            if (req == null)
                throw new CustomException("打印机连接失败");
            return req.getString("Result") != null;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 获取请求头
     */
    private static Map<String, String> getHeader() {
        Map<String, String> header = new HashMap<>();
        header.put("Cache-Control", "no-cache");
        header.put("Connection", "keep-alive");
        header.put("Accept", "*/*");
        header.put("Content-Type", "application/json");
        header.put("Accept-Language", "zh-CN,zh;q=0.9");
        header.put("Accept-Encoding", "gzip, deflate, br");
//        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        return header;
    }

    private static Map<String, String> getHeader(String printModel) {
        Map<String, String> header = new HashMap<>();
        header.put("Cache-Control", "no-cache");
        header.put("Connection", "keep-alive");
        header.put("Accept", "*/*");
        if (PrintConsts.PRINT_MODE_PHOTO.equals(printModel))
            header.put("Content-Type", "image/jpeg");
        else
            header.put("Content-Type", "application/octet-stream");
        header.put("Accept-Language", "zh-CN,zh;q=0.9");
        header.put("Accept-Encoding", "gzip, deflate, br");
//        header.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
        return header;
    }
}
